/**
 * base64转化为路径
 */
export function base64ToPath(base64Str: string) {
  let base64 = base64Str;
  return new Promise((resolve, reject) => {
    // #ifdef H5
    const base64Arr = base64.split(',');
    const type = base64Arr[0]!.match(/:(.*?);/)![1];
    const str = window.atob(base64Arr[1]!);
    let n = str.length;
    const array = new Uint8Array(n);
    while (n--) {
      array[n] = str.charCodeAt(n);
    }
    resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type })));
    // #endif

    // #ifdef APP-PLUS || MP-WEIXIN
    const extNameSrt = base64.substring(0, 40);
    const extNameArr = extNameSrt.match(/data:\S+\/(\S+);/)!;
    let extName = '';
    if (extName) {
      extName = extNameArr[1]!;
    } else {
      reject(new Error('base64 error'));
    }
    const fileName = `${Date.now()}.${extName}`;
    // #endif

    // #ifdef APP-PLUS
    const bitmap = new plus.nativeObj.Bitmap!();
    bitmap.loadBase64Data(
      base64,
      () => {
        const filePath = `_doc/uniapp_temp/${fileName}`;
        bitmap.save(
          filePath,
          {},
          () => {
            bitmap.clear();
            resolve(filePath);
          },
          (error) => {
            bitmap.clear();
            reject(error);
          }
        );
      },
      (error) => {
        bitmap.clear();
        reject(error);
      }
    );
    // #endif

    // #ifdef MP-WEIXIN
    const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
    base64 = base64.substring(extNameSrt.indexOf(';base64,') + 8);
    uni.getFileSystemManager().writeFile({
      filePath,
      data: base64,
      encoding: 'base64',
      success() {
        resolve(filePath);
      },
      fail(error) {
        reject(error);
      },
    });
    // #endif
  });
}

/**
 * 路径转化为base64 (仅针对图片)
 */
export function pathToBase64(path: string) {
  return new Promise((resolve, reject) => {
    // #ifdef H5
    if (typeof FileReader === 'function') {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', path, true);
      xhr.responseType = 'blob';
      // eslint-disable-next-line func-names
      xhr.onload = function () {
        if (this.status === 200) {
          const fileReader = new FileReader();
          // eslint-disable-next-line func-names
          fileReader.onload = function (e) {
            resolve(e.target!.result);
          };
          fileReader.onerror = reject;
          fileReader.readAsDataURL(this.response);
        }
      };
      // eslint-disable-next-line func-names
      xhr.onerror = function () {
        reject(false);
      };
      xhr.send();
    } else {
      const canvas = document.createElement('canvas');
      const c2x = canvas.getContext('2d');
      const img = new Image();
      img.onload = () => {
        canvas.width = img.width;
        canvas.height = img.height;
        c2x!.drawImage(img, 0, 0);
        resolve(canvas.toDataURL());
        canvas.height = 0;
        canvas.width = 0;
      };
      img.onerror = () => {
        reject(false);
      };
      img.src = path;
    }
    // #endif

    // #ifdef APP-PLUS
    const savedFilePath = plus.io.convertLocalFileSystemURL(path); // 绝对路径
    const fileReader = new plus.io.FileReader!();
    fileReader.readAsDataURL(savedFilePath as any);
    fileReader.onloadend = (res) => {
      // 读取文件成功完成的回调函数
      resolve('result' in res.target! ? (res.target.result as string) : '');
    };
    fileReader.onerror = (err) => {
      console.log('error====', err);
      reject('路径生成base64失败，-1001');
    };
    // #endif

    // #ifdef MP-WEIXIN
    uni.getFileSystemManager().readFile({
      filePath: path,
      encoding: 'base64',
      success(res) {
        resolve(`data:image/png;base64,${res.data}`);
      },
      fail(error) {
        reject(error);
      },
    });
    // #endif
  });
}

/** 创建用于 canvas 的 img */
export function createImage(canvas?: any) {
  if (canvas && canvas.createImage) {
    return canvas.createImage();
  } else if ((canvas.tagName === 'canvas' && !('toBlob' in canvas)) || (canvas && !('toBlob' in canvas))) {
    return new Image();
  } else if (typeof window !== 'undefined') {
    return new window.Image();
  }
  return new Image();
}
